
//
//  CommunityViewController.swift
//  ZCF
//
//  Created by 赵世杰 on 16/3/15.
//  Copyright © 2016年 zhaoshijie. All rights reserved.
//

import UIKit


class CommunityViewController: BaseViewController,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate
{
    
    /// 变量
    
    
    // button选择文字数组
    var titleButtonArray:Array<String>!
    // button的图片数组(未选中)
    var imageOnButtonArray:Array<String>!
    // button的图片数组(选中)
    var imageUpButtonArray:Array<String>!
    // tableView的页数
    var currentPage:Int!
    // 当前界面
    var PageNumber:Int!
    
    
    /// model数据
    
    // 头视图图片数组
    var headScrollImageArray:Array<AnyObject>!
    // cell里面所有的数据
    var cellDataList:Array<AnyObject>!
    // cell热门的数据
    var hotCellDataList:Array<AnyObject>!
    // cell精选的数据
    var selectedCellDataList:Array<AnyObject>!
    // 休闲娱乐
    var amusementCellDatList:Array<AnyObject>!
    
    /// 视图
    
    // 头视图
    var tableViewHeader:UIView!
    // 滑动视图
    var scrollView:UIScrollView!

    @IBOutlet var overallTableView: UITableView!
    
    override func viewWillAppear(_ animated: Bool){
        self.navigationController?.navigationBar.barTintColor = CommonTool.color(withHexString: "2a9df7")
        UIView.animate(withDuration: 0.2, animations: { () -> Void in
            self.navigationController?.navigationBar.isHidden = true
            self.tabBarController?.tabBar.isHidden = true
        }) 
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        UIView.animate(withDuration: 0.2, animations: { () -> Void in
            self.navigationController?.navigationBar.isHidden = false

        }) 
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        
        
        // 设置导航栏透明
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor ( red: 0.9137, green: 0.9042, blue: 0.9232, alpha: 1.0 )
        
        
        // 初始化数据
        self._initDataList()
        
        // 创建子视图
        self._initViews()
        
        
        // 请求数据
        self._requestDataList()
    }
    
    
    //MARK: - 方法
    // 初始化数据
    func _initDataList()
    {
        self.headScrollImageArray = Array<AnyObject>()
        self.cellDataList = Array<AnyObject>()
        self.currentPage = 1 ;
        self.PageNumber = 0 ;
        self.titleButtonArray = ["热门","精选","休闲娱乐","分享"]
        self.imageOnButtonArray = ["sq_07","sq_09","sq_11","sq_13"]
        self.imageUpButtonArray = ["sqd_03","sqd_05","sqd_07","sqd_09"]
    }
    
    // 创建视图
    func _initViews()
    {
        self._creattableViewHeaderView()
        self.overallTableView.delegate = self
        self.overallTableView.dataSource = self
        self.overallTableView.separatorStyle = .none
        // 设置cell的自适应高度
        self.overallTableView.rowHeight = UITableViewAutomaticDimension
//        self.overallTableView.estimatedRowHeight = 100 
        // 设置上拉刷新，下拉加载
        self.overallTableView.addHeader(withTarget: self, action: #selector(CommunityViewController.refreshHeadedAction))
        self.overallTableView.addFooter(withTarget: self, action: #selector(CommunityViewController.refreshFootedAction))
        
        
        // 注册单元格
        self.overallTableView .register(UINib(nibName: "ShareContentTableViewCell1", bundle: nil), forCellReuseIdentifier: "cellID1")
        self.overallTableView .register(UINib(nibName: "ShareContentTableViewCell2", bundle: nil), forCellReuseIdentifier: "cellID2")
        
    }
    
    func _creattableViewHeaderView()
    {
        // 透视图的整体视图
        self.tableViewHeader = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 232*(KScreenWidth/640) + 5 + (KScreenWidth-CGFloat(130))/4.0 + 20 + 5))
        self.overallTableView.tableHeaderView = self.tableViewHeader
        
        // 创建button选择按钮
        for i in 0  ..< self.titleButtonArray.count 
        {
            let width = 20+((KScreenWidth-CGFloat(130))/4.0+30)*CGFloat(i)
            let button = UIButton(type: .custom)
            button.frame = CGRect(x: width, y: 232*(KScreenWidth/640)+5, width: (KScreenWidth-CGFloat(130))/4.0, height: (KScreenWidth-CGFloat(130))/4.0)
            button.tag = 120 + i
            button.setImage(UIImage(named: self.imageOnButtonArray[i]), for: UIControlState())
            button.setImage(UIImage(named: self.imageUpButtonArray[i]), for: .selected)
            button.addTarget(self, action: #selector(CommunityViewController.buttonAction(_:)), for: .touchUpInside)
            self.tableViewHeader.addSubview(button)
            if i == 0
            {
                button.isSelected = true
            }
            
            
            let label = UILabel(frame: CGRect(x: button.left, y: button.bottom, width: button.width, height: 20))
            label.font = UIFont.systemFont(ofSize: 10)
            label.text = self.titleButtonArray[i]
            label.textAlignment = .center
            self.tableViewHeader.addSubview(label)
            
        }
    }
    
    func requestSuccessNext()
    {
        self.scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 232*(KScreenWidth/640)))
        // 创建放在滑动视图上面的图片
        var array:Array<AnyObject> = Array()
        for i in 0  ..< self.headScrollImageArray.count 
        {
            let HSmodel_COM = self.headScrollImageArray[i] as! HeadScrllerModel_Community
            array.append(HSmodel_COM.url as AnyObject)
        }
        self.tableViewHeader.addSubview(self.scrollView)
        self.scrollView.addImageToScrollView(withImagesArray: array)
        
    }
    
    //MARK: - 数据请求
    func _requestDataList()
    {
        
        // 请求头视图数据
        self.requestHeadScroll()
        
        // 请求cell的数据
        self.requestCell(PullState.dropDown)
    }
    
    
    /**
     请求头视图数据
     */
    func requestHeadScroll()
    {
        let urlString = HttpUrl + "/bbs/banner/image/get"
        let requestHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let request = HTTPRequest()
        request.POSTRequest(urlString, httpHeader: requestHeader, parameters: nil, resultBlock: { (result) -> Void in
//            print("请求成功")
//            print(result)
            // 取数据
            let data:Array<AnyObject> = result["data"] as! Array
            for dic:AnyObject in data
            {
                let HSmodel_COM = HeadScrllerModel_Community()
                HSmodel_COM.initWithDictionary(dic)
                self.headScrollImageArray.append(HSmodel_COM)
            }
            
            // 刷新一下视图
            self.requestSuccessNext()
            
            }) { () -> Void in
                print("请求失败")
        }
        
    }
    
    
    /**
     请求cell的数据
     */
    func requestCell(_ state:PullState)
    {
        let urlString = HttpUrl + "/bbs/page/get"
        let requestHeader:[String:String] = ["version":"2.0","terminal":"ios"]
        let request = HTTPRequest()
        var dic:[String:String] = Dictionary()
        if self.PageNumber == 0
        {
            dic = ["page":String(self.currentPage)]
        }
        else
        {
            dic = ["page":String(self.currentPage),"typeId":String(self.PageNumber)]
        }
        request.POSTRequest(urlString, httpHeader: requestHeader, parameters: dic, resultBlock: { (result) -> Void in
//            print("请求成功")
//            print(result)
            // 下拉时清空数据
            if state == PullState.dropDown
            {
                self.cellDataList.removeAll()
                self.currentPage = 1
                self.PageNumber = 0
            }
            // 取数据
            let data:Dictionary<String,AnyObject> = result["data"] as! Dictionary
            // 设置页数
            self.currentPage = self.currentPage + 1
            let list:Array<AnyObject> = data["list"] as! Array
            for dic:AnyObject in list
            {
                let cellModel_COM = CellModel_community(contentDic:dic as! [AnyHashable: Any])
                self.cellDataList.append(cellModel_COM!)
            }
            // 刷新tableView
            self.overallTableView.reloadData()
            // 停止加载
            self.stopLoadRefreshView()
            
            }) { () -> Void in
//                print("请求失败")
        }
    }
    
    //MARK: - button等控件的响应事件
    func buttonAction(_ sender:UIButton)
    {
        self.currentPage = 1
        for i in 0  ..< self.imageOnButtonArray.count 
        {
            let button = self.tableViewHeader.viewWithTag(120+i) as! UIButton
            button.isSelected = false
        }
        sender.isSelected = true
        
        if sender.tag != self.PageNumber
        {
            self.cellDataList.removeAll()
        }
        if sender.tag == 123
        {
            return
        }
        if sender.tag == 120
        {
            self.PageNumber = 0
        }
        else if sender.tag == 121
        {
            self.PageNumber = 1
        }
        else if sender.tag == 122
        {
            self.PageNumber = 2
        }
        self.requestCell(PullState.dropDown) ;
    }
    
    
    //MARK: - 停止加载
    func stopLoadRefreshView()
    {
        if self.overallTableView.isHeaderRefreshing
        {
            self.overallTableView.headerEndRefreshing()
        }
        else
        {
            self.overallTableView.footerEndRefreshing()
        }
    }
    
    /**
     上拉加载，下拉刷新
     */
    func refreshHeadedAction()
    {
        self.requestCell(PullState.dropDown)
    }
    
    func refreshFootedAction()
    {
        self.requestCell(PullState.pullOn)
    }
    
    
    //MARK: - tableView的代理和数据源方法 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.cellDataList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel_COM = self.cellDataList[(indexPath as NSIndexPath).row] as! CellModel_community
        let imageArray:Array<AnyObject> = cellModel_COM.imageList as Array
        if imageArray.isEmpty
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellID1") as! ShareContentTableViewCell1
            cell.selectionStyle = .none
            cell.cellModel_COM = cellModel_COM
            // 刷新单元格
            cell.layoutIfNeeded()
            return cell
        }
        else
        {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellID2") as! ShareContentTableViewCell2
            cell.selectionStyle = .none
            cell.cellModel_COM = cellModel_COM
            // 刷新单元格
            cell.layoutIfNeeded()
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let postDetailsVC = PostDetailsViewController()
        let cellModel_COM = self.cellDataList[(indexPath as NSIndexPath).row] as! CellModel_community
        let id = String(describing: cellModel_COM.id)
        postDetailsVC.messagedId = id
        postDetailsVC.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(postDetailsVC, animated: true)
    }
    
    /**
     设置cell的高度
     */
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.computeCellHeight(self.cellDataList[(indexPath as NSIndexPath).row] as! CellModel_community)
    }
    
    //MARK: - 计算cell的高度
    func computeCellHeight(_ cellmol:CellModel_community) -> CGFloat
    {
        var height:CGFloat = 5 + 5 + 40 + 10 + self.textLabelheight(cellmol.title ,size: 16) + 5 + self.textLabelheight(cellmol.content , size: 15) + 10 + 30 + 5 + 5
        if !cellmol.imageList.isEmpty
        {
            height = height + (KScreenWidth-10-30)/CGFloat(3) + 15
        }
        
        return height
    }
    
    
    //MARK: - 计算文本的高度
    func textLabelheight(_ textString:String , size:CGFloat) -> CGFloat
    {
        let attributus = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: size)]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let text:NSString = NSString(cString: textString.cString(using: String.Encoding.utf8)!, encoding: String.Encoding.utf8.rawValue)!
        let rect = text.boundingRect(with: CGSize(width: KScreenWidth-20, height: 1000), options: option, attributes: attributus, context: nil)
        return rect.height
    }

}
